package com.jiang.blackjack

import android.content.DialogInterface
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.jiang.blackjack.adapter.BJAdapter
import com.jiang.blackjack.card.Dealer
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    lateinit var dealer: Dealer
    lateinit var adapterP: BJAdapter
    lateinit var adapterD: BJAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        dealer = Dealer()
        init()
        initListener()
    }

    private fun initListener() {
        btn_draw.setOnClickListener {
            if (!dealer.draw(true)) {
                Toast.makeText(this, "不能再要牌", Toast.LENGTH_SHORT).show()
            }
            dealer.thinking()
            refreshUI()
            if (dealer.checkBurst(true)) {
                dealer.judge()
                createDialog()
            }
        }
        btn_judge.setOnClickListener {
            dealer.thinking()
            adapterD = BJAdapter(this, dealer.dealerCards, true)
            lv_dealer.adapter = adapterD
            dealer.judge()
            createDialog()
        }
    }

    private fun createDialog() {
        AlertDialog.Builder(this)
            .setTitle(if (dealer.isWin) "Win" else "Lose")
            .setMessage(dealer.result)
            .setPositiveButton("ok") { _, _ -> init() }
            .show()
    }

    private fun init() {
        initView()
        dealer.start()
        refreshUI()
    }

    private fun initView() {
        adapterP = BJAdapter(this, dealer.playerCards, true)
        lv_player.adapter = adapterP
        adapterD = BJAdapter(this, dealer.dealerCards, false)
        lv_dealer.adapter = adapterD
    }

    private fun refreshUI() {
        adapterP.notifyDataSetChanged()
        adapterD.notifyDataSetChanged()
        tv.text = "${dealer.playerValue}"
    }
}
